package com.bonc.ioc.demo.config;

import com.bonc.ioc.demo.exception.McpException;
import com.bonc.ioc.demo.utils.HttpParameterUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * * @description Feign调用添加token
 *
 * @author jin.xu@hand-china.com
 * @date 2020/12/1 12:03
 * @change: 2020/12/1 12:03 by jin.xu@hand-china.com for init
 */
@Configuration
public class FeignRequestConfig implements RequestInterceptor {
    @Value("${spring.application.name:null}")
    private String applicationName;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // header添加token
        requestTemplate.header("tokenId", request.getHeader("tokenId"));

        requestTemplate.header("Referer", request.getHeader("Referer"));
        requestTemplate.header("requestServiceName", applicationName);

        if (FilterConfig.testDecryptFilterFlag) {
            try {
                HttpParameterUtil.encryptGetParameter(requestTemplate);
            } catch (IOException e) {
                throw new McpException("fegin解密http加密设置异常" + e.toString());
            } catch (ServletException e) {
                throw new McpException("fegin解密http加密设置异常" + e.toString());
            }

        }
    }
}
